import BaseView from "../../../Script/Base/BaseView";
import { EBundleType, EResType, EViewType } from "../../../Script/Common/Enum";
import EventID from "../../../Script/Common/EventID";
import { GlobalData } from "../../../Script/Common/GlobalData";
import { TalkModule } from "../../../Script/Common/TalkModule";
import { IFlyResData, IGameData, IMessage, IViewData } from "../../../Script/Interface/IMessage";
import { SceneGame } from "../../../Script/SceneGame";
import AppService from "../../../Script/Service/AppService";
import GameUtil from "../../../Script/Util/GameUtil";
import StorageUtil from "../../../Script/Util/StorageUtil";
import TaskModule from "../../Common/TaskModule";
import { AdManager } from "../../naodong/ads/AdManager";
import GameUI from "../GameUI";
import CollectItem from "./CollectItem";
import TownUI from "./TownUI";

const { ccclass, property } = cc._decorator;

const VIEW_DATA: IViewData = {
    name: 'CollectUI',
    type: EViewType.Panel,
    bundle: EBundleType.Game,
    zIndex: 100,
};

@ccclass
export default class CollectUI extends BaseView implements IMessage {

    @property({ type: cc.Node, tooltip: "列表节点" })
    private items: cc.Node = null;

    @property({ type: cc.Label, tooltip: "收购总价" })
    private labTotal: cc.Label = null;

    private itemNodes: cc.Node[] = [];
    private total: number = 0;

    private gameData: IGameData = null;

    recvMsg(cmd: number, data: any) {
        switch (cmd) {
            case EventID.TEST_CMD:
                {

                }
                break;
        }
    }

    protected onLoad() {
        super.onLoad();
        this.addMessage(EventID.TEST_CMD, this);

        this.gameData = StorageUtil.instance.getGameData();

        this.initView();
    }

    private check() {
        const talkData = StorageUtil.instance.getTalkData();
        switch (talkData.id) {
            case 10510:
                {
                    talkData.id = 10551;
                    // 任务数据
                    TaskModule.instance.saveData();
                }
                break;
            case 11001:
                {
                    talkData.id = 11006;
                    // 任务数据
                    TaskModule.instance.saveData();
                }
                break;
        }
        console.log("Collect.onBtnClicked()===>当前完成id:", talkData.id);
    }

    private initView() {
        const collect = GlobalData.getCollectData();
        for (let i = this.itemNodes.length - 1; i > -1; i--) {
            const node = this.itemNodes[i];
            if (node && node.active) {
                node.destroy();
            }
        }
        this.itemNodes = [];
        
        for (let i = 0; i < collect.needs.length; i++) {
            const need = collect.needs[i];
            const item = this.items.children[0];
            const node = cc.instantiate(item);
            node.parent = this.items;
            node.active = true;
            node.getComponent(CollectItem).setData(need);
            this.itemNodes.push(node);
        }

        this.countTotalPrice();
    }

    private countTotalPrice() {
        this.total = 0;
        this.itemNodes.forEach((o) => {
            const real = o.getComponent(CollectItem).getRealPrice();
            this.total += real.price;
        });

        this.labTotal.string = `收购总价:${GameUtil.changeUnit(this.total, 2)}`;
    }

    private isAllComplete() {
        for (let i = 0; i < this.itemNodes.length; i++) {
            const item = this.itemNodes[i];
            const complete = item.getComponent(CollectItem).getComplete();
            if (!complete) {
                return false;
            }
        }
        return true;
    }

    public onCloseChild() {
        if (this.isHasChild) {
            this.isHasChild = false;
            this.initView();
        }
    }

    public async onCloseClicked() {
        super.onCloseClicked();

        await GameUtil.sleep(500);
        TalkModule.updateCheck();
        TownUI.instance?.check();
        GameUI.instance?.check();
    }

    private onBtnsClicked(event: cc.Event.EventTouch, eventData: string) {
        const name = event.target.name;
        switch (name) {
            case 'btnSale':
                {
                    const isComplete = this.isAllComplete();
                    if (!isComplete) {
                        SceneGame.instance.showToast(cc.v2(0, 0), "去矿山完成收集任务吧~");
                        return;
                    }

                    // 重置加价次数
                    this.gameData.addPriceCount = 0;
                    // 交货
                    GlobalData.deleteCollect();
                    // 更新
                    this.check();

                    if (this.total > 0) {
                        SceneGame.instance.showTopMask();
                        const data = SceneGame.instance.getFlyResData();
                        const flyData: IFlyResData = {
                            resType: EResType.Money,
                            parent: data.flyNode,
                            from: this.node,
                            to: data.money,
                            value: this.total,
                            flyTimes: 20,
                            maxWidth: 60,
                            maxHeight: 60
                        }
                        GameUtil.instance.flyResIcon(flyData);

                        setTimeout(() => {
                            // 关闭弹窗
                            SceneGame.instance.hideTopMask();
                            SceneGame.instance.removePopView(this.node);
                        }, 300);
                    }
                }
                break;
            case 'btnAdd':
                {
                    if (this.gameData.addPriceCount < 4) {
                        // 播放视频
                        AdManager.showVideoAd(() => {
                            this.gameData.addPriceCount++;
                            this.itemNodes.forEach((o) => {
                                o.getComponent(CollectItem).refresh();
                            });
                            this.countTotalPrice();
                        });
                    } else {
                        SceneGame.instance.showToast(cc.v2(0, 0), '已是当前最高价格~');
                    }
                }
                break;
        }
    }
}
AppService.instance.registViewData(VIEW_DATA);